package com.vitabuybuy.tv.ui.home

import android.location.Location
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout
import com.google.gson.reflect.TypeToken
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseFragment
import com.library.common.base.MessageModel
import com.library.common.ext.logE
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.util.DensityUtil
import com.library.common.util.JsonUtil
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.adaptebinding.ImageAdapter.setNomalImageUrl
import com.vitabuybuy.tv.adaptebinding.TextAdapter.setNowPrice
import com.vitabuybuy.tv.databinding.FragmentHomeBinding
import com.vitabuybuy.tv.dto.*
import com.vitabuybuy.tv.ui.WebViewActivity
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.home.adapter.GoodsAdapter
import com.vitabuybuy.tv.ui.home.adapter.LiveAdapter
import com.vitabuybuy.tv.ui.home.bidd.BiddingCommodityActivity
import com.vitabuybuy.tv.ui.home.bidd.BiddingZoneActivity
import com.vitabuybuy.tv.ui.home.bidd.adapter.BiddingZoneAdapter
import com.vitabuybuy.tv.ui.home.coupons.CouponsCenterActivity
import com.vitabuybuy.tv.ui.home.group.GroupBuyDetailActivity
import com.vitabuybuy.tv.ui.home.group.GroupBuyZoneActivity
import com.vitabuybuy.tv.ui.home.group.adapter.GroupBuyListZoneAdapter
import com.vitabuybuy.tv.ui.home.live.LiveZoneActivity
import com.vitabuybuy.tv.ui.home.viewmodel.HomeViewModel
import com.vitabuybuy.tv.ui.shopcenter.CommodityClassificationActivity
import com.vitabuybuy.tv.ui.shopcenter.GoodsDetailsActivity
import com.vitabuybuy.tv.ui.shopcenter.SearchGoodsOrStoreActivity
import com.vitabuybuy.tv.ui.tencent.chat.MessageListActivity
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.RoomInfo
import com.vitabuybuy.tv.ui.tencent.liveroom.ui.AudienceLiveRoomActivity
import com.vitabuybuy.tv.utils.GetAddressUtil
import com.vitabuybuy.tv.utils.LocationUtil
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import kotlinx.android.synthetic.main.fragment_home.*

/**
 * 作者：SimGa
 * 日期：2020/11/29
 * 时间：10:49
 * 包名：com.vitabuybuy.tv.ui.cart
 */

class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>() {
    override val layoutId: Int
        get() = R.layout.fragment_home

    private var areaDialog: BottomDialog? = null
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var regionId: Int? = -1
    private val goodAdpter by lazy { GoodsAdapter() }
    private val liveAdpter by lazy { LiveAdapter() }
    private val groupAdpter by lazy { GroupBuyListZoneAdapter() }
    private val biddingAdpter by lazy { BiddingZoneAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.viewModel = viewModel
        initBanner()
        listView.apply {
            layoutManager = GridLayoutManager(mContext, 2)
            adapter = goodAdpter
            isNestedScrollingEnabled = false
        }
        val titles = arrayListOf(
            getString(R.string.all),
            getString(R.string.live),
            getString(R.string.go_dutch),
            getString(R.string.bidding)
        )
        for (i in titles.indices) {
            mTabEntities.add(
                TabDto(titles[i], 0, 0)
            )
        }
        tl_title.setTabData(mTabEntities)

        LocationUtil.getCurrentLocation(mContext, object : LocationUtil.LocationCallBack {
            override fun onSuccess(location: Location) {
                val address = GetAddressUtil(mContext).getAddress(
                    location.longitude,
                    location.latitude
                )
                if (!address.isNullOrEmpty()) {
                    val add = address[0]
                    tv_loaction.text = add.countryName
                }
            }

            override fun onFail(msg: String) {
            }
        })
    }

    override fun lazyLoadData() {
        viewModel.getHomeData(regionId, true)
    }

    override fun observeData() {
        viewModel.homeData.observe(this, Observer {
            refresh.finishRefreshLoadingMore()
            goodAdpter.setNewData(it.goodlist)
            liveAdpter.setNewData(it.livelist)
            groupAdpter.setNewData(it.groupGoodlist)
            biddingAdpter.setNewData(it.biddingGoodlist)
            showEmptyView()
            my_banner.setBannerData(it.bannerlist.slideList)
            setActivityView(it.bannerlist)

            mmkv.encode(MMKVContancts.CATEGORY_LIST, JsonUtil.toJson(it.categoryList))
            tlClassification.apply {
                removeAllTabs()
                addTab(tlClassification.newTab().setText(getString(R.string.home)))
                for (str in it.categoryList) {
                    addTab(tlClassification.newTab().setText(str.name))
                }
                //不执行下面这一句，下拉刷新tab会滚动，暂时找不到原因
                scrollTo(0,0)
            }
        })
    }

    //显示活动版块
    private fun setActivityView(it: BannerDto) {
        when (it.couponList.size) {
            0 -> {
                rlGoodCoupons1.visibility = View.INVISIBLE
                rlGoodCoupons2.visibility = View.INVISIBLE
            }
            1 -> {
                rlGoodCoupons1.visibility = View.VISIBLE
                rlGoodCoupons2.visibility = View.INVISIBLE
                rlGoodCoupons1.tag = it.couponList[0]
                tvGoodCoupons1.text = if (it.couponList[0].precondition == 0)
                    getString(R.string.no_threshold)
                else
                    String.format(
                        getString(R.string.lijian),
                        it.couponList[0].discount
                    )
            }
            else -> {
                rlGoodCoupons1.visibility = View.VISIBLE
                rlGoodCoupons2.visibility = View.VISIBLE
                rlGoodCoupons1.tag = it.couponList[0]
                rlGoodCoupons2.tag = it.couponList[1]
                tvGoodCoupons1.text = if (it.couponList[0].precondition == 0)
                    getString(R.string.no_threshold)
                else
                    String.format(
                        getString(R.string.lijian),
                        it.couponList[0].discount
                    )
                tvGoodCoupons2.text = if (it.couponList[1].precondition == 0)
                    getString(R.string.no_threshold)
                else
                    String.format(
                        getString(R.string.lijian),
                        it.couponList[1].discount
                    )
            }
        }
        when (it.biddingList.size) {
            0 -> {
                rlLimitedTimeBidding1.visibility = View.INVISIBLE
                rlLimitedTimeBidding2.visibility = View.INVISIBLE
            }
            1 -> {
                rlLimitedTimeBidding1.visibility = View.VISIBLE
                rlLimitedTimeBidding2.visibility = View.INVISIBLE
                rlLimitedTimeBidding1.tag = it.biddingList[0]
                setNomalImageUrl(
                    ivLimitedTimeBidding1,
                    it.biddingList[0].product.thumbnail,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                tvLimitedTimeBidding1.text =
                    getString(R.string.start_bidding) + String.format(
                        getString(R.string.price_with_value),
                        it.biddingList[0].startingPrice
                    )
            }
            else -> {
                rlLimitedTimeBidding1.visibility = View.VISIBLE
                rlLimitedTimeBidding2.visibility = View.VISIBLE
                rlLimitedTimeBidding1.tag = it.biddingList[0]
                rlLimitedTimeBidding2.tag = it.biddingList[1]
                setNomalImageUrl(
                    ivLimitedTimeBidding1,
                    it.biddingList[0].product.thumbnail,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                tvLimitedTimeBidding1.text =
                    getString(R.string.start_bidding) + String.format(
                        getString(R.string.price_with_value),
                        it.biddingList[0].startingPrice
                    )
                setNomalImageUrl(
                    ivLimitedTimeBidding2,
                    it.biddingList[1].product.thumbnail,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                tvLimitedTimeBidding2.text =
                    getString(R.string.start_bidding) + String.format(
                        getString(R.string.price_with_value),
                        it.biddingList[1].startingPrice
                    )
            }
        }
        when (it.groupBuyingList.size) {
            0 -> {
                rlHotGroupBuy1.visibility = View.INVISIBLE
                rlHotGroupBuy2.visibility = View.INVISIBLE
            }
            1 -> {
                rlHotGroupBuy1.visibility = View.VISIBLE
                rlHotGroupBuy2.visibility = View.INVISIBLE
                rlHotGroupBuy1.tag = it.groupBuyingList[0]
                setNomalImageUrl(
                    ivHotGroupBuy1,
                    it.groupBuyingList[0].product.thumbnail,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                setNowPrice(tvHotGroupBuy1, it.groupBuyingList[0].product.promotionPrice)
            }
            else -> {
                rlHotGroupBuy1.visibility = View.VISIBLE
                rlHotGroupBuy2.visibility = View.VISIBLE
                rlHotGroupBuy1.tag = it.groupBuyingList[0]
                rlHotGroupBuy2.tag = it.groupBuyingList[1]
                setNomalImageUrl(
                    ivHotGroupBuy1,
                    it.groupBuyingList[0].product.thumbnail,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                setNowPrice(tvHotGroupBuy1, it.groupBuyingList[0].product.promotionPrice)

                setNomalImageUrl(
                    ivHotGroupBuy2,
                    it.groupBuyingList[1].product.thumbnail,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                setNowPrice(tvHotGroupBuy2, it.groupBuyingList[1].product.promotionPrice)
            }
        }
        when (it.liveList.size) {
            0 -> {
                rlPopularLive1.visibility = View.INVISIBLE
                rlPopularLive2.visibility = View.INVISIBLE
            }
            1 -> {
                rlPopularLive1.visibility = View.VISIBLE
                rlPopularLive2.visibility = View.INVISIBLE
                rlPopularLive1.tag = it.liveList[0]
                setNomalImageUrl(
                    ivPopularLive1,
                    it.liveList[0].image,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                if (it.liveList[0].productList.size > 0) {
                    setNowPrice(tvPopularLive1, it.liveList[0].productList[0].salePrice)
                }
            }
            else -> {
                rlPopularLive1.visibility = View.VISIBLE
                rlPopularLive2.visibility = View.VISIBLE
                rlPopularLive1.tag = it.liveList[0]
                rlPopularLive2.tag = it.liveList[1]
                setNomalImageUrl(
                    ivPopularLive1,
                    it.liveList[0].image,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                setNomalImageUrl(
                    ivPopularLive2,
                    it.liveList[1].image,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                if (it.liveList[0].productList.size > 0) {
                    setNowPrice(tvPopularLive1, it.liveList[0].productList[0].salePrice)
                } else {
                    tvPopularLive1.text = "直播中"
                }
                if (it.liveList[1].productList.size > 0) {
                    setNowPrice(tvPopularLive2, it.liveList[1].productList[0].salePrice)
                } else {
                    tvPopularLive2.text = "直播中"
                }
            }
        }
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            ivLive, rlPopularLive1, rlPopularLive2,
            ivClassification, rlSearch, ivBidding, ivGroupBuy,
            ivGetCoupons, rlHotGroupBuy1, rlHotGroupBuy2, rlLimitedTimeBidding1,
            rlLimitedTimeBidding2, rlGoodCoupons1, rlGoodCoupons2, tv_loaction,
            ivMessage
        ){v->
            when (v) {
                rlSearch -> SearchGoodsOrStoreActivity.openActivity(mContext)
                ivLive -> LiveZoneActivity.openActivity(mContext)
                ivGroupBuy -> GroupBuyZoneActivity.openActivity(mContext)
                ivBidding -> BiddingZoneActivity.openActivity(mContext)
                ivGetCoupons -> CouponsCenterActivity.openActivity(mContext)
                rlPopularLive2,
                rlPopularLive1 -> {
                    LiveZoneActivity.openActivity(mContext)
                }
                rlHotGroupBuy1 -> {
                    val data = v.tag as BannerDto.GroupBuyingListBean
                    GroupBuyDetailActivity.openActivity(mContext, data.id)
                }
                rlHotGroupBuy2 -> {
                    val data = v.tag as BannerDto.GroupBuyingListBean
                    GroupBuyDetailActivity.openActivity(mContext, data.id)
                }
                rlLimitedTimeBidding1 -> {
                    val data = v.tag as BannerDto.BiddingListBean
                    BiddingCommodityActivity.openActivity(mContext, data.product.id, data.id)
                }
                rlLimitedTimeBidding2 -> {
                    val data = v.tag as BannerDto.BiddingListBean
                    BiddingCommodityActivity.openActivity(mContext, data.product.id, data.id)
                }
                rlGoodCoupons1 -> CouponsCenterActivity.openActivity(mContext)
                rlGoodCoupons2 -> CouponsCenterActivity.openActivity(mContext)
                ivClassification -> CommodityClassificationActivity.openActivity(
                    mContext,
                    CommodityClassificationActivity.FROM_GOODS_CENTER
                )
                tv_loaction -> {
                    //这里一定要重新创建
                    areaDialog = BottomDialog(mContext, 1)
                    viewModel.getRegionList(null)
                }
                ivMessage -> MessageListActivity.openActivity(mContext)
            }
        }
        tl_title.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
//                showEmptyView(position)
                viewModel.getTabHomeData(position)
            }
            override fun onTabReselect(position: Int) {}
        })
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                viewModel.getHomeData(regionId, true)
            }
        })
        tlClassification.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (tab?.text == getString(R.string.home))
                    return
                CommodityClassificationActivity.openActivity(
                    mContext,
                    tab?.text?.toString(),
                    CommodityClassificationActivity.FROM_GOODS_CENTER
                )
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                if (tab?.text == getString(R.string.home))
                    return
                CommodityClassificationActivity.openActivity(
                    mContext,
                    tab?.text?.toString(),
                    CommodityClassificationActivity.FROM_GOODS_CENTER
                )
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }
        })
        goodAdpter.setOnItemClickListener { _, item, _ ->
            GoodsDetailsActivity.openActivity(mContext, item.id)
        }
        liveAdpter.onItemCLickListener = { item ->
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
            } else {
                val roomInfo = RoomInfo().apply {
                    audienceCount = item.viewerQuantity
                    roomID = item.roomNumber
                    roomInfo = item.title
                    roomName = item.title
                    mixedPlayURL = item.playUrl
                    authorRegion = item.allRegion
                    liveId = item.id
                    attention = item.isAttention
                    item.store?.let {
                        roomCreator = it.id.toString()
                        authorName = it.name
                        authorId = it.id.toString()
                        authorAvatar = it.logo
                        isExecutor = false
                    } ?: let {
                        item.executor?.let {
                            roomCreator = it.id.toString()
                            authorName = it.realname
                            authorId = it.id.toString()
                            authorAvatar = it.avatar
                            isExecutor = true
                        }
                    }
                    userId = mmkv.decodeInt(MMKVContancts.USER_ID).toString()
                    userName = mmkv.decodeString(MMKVContancts.USER_NICKNAME)
                    createRoom = false
                }
                AudienceLiveRoomActivity.openActivity(mContext, roomInfo)
            }
        }
        groupAdpter.setOnItemClickListener { _, item, _ ->
            GroupBuyDetailActivity.openActivity(mContext, item.id)
        }
        biddingAdpter.setOnItemClickListener { _, item, _ ->
            BiddingCommodityActivity.openActivity(mContext, item.product.id, item.id)
        }
        my_banner.setOnItemClickListener { _, model, view, position ->
            val bannerDto = model as BannerDto.SlideListBean
            when (bannerDto.type) {
                "page" -> {
                    WebViewActivity.openActivity(mContext, "", "", Integer.parseInt(bannerDto.link))
                }
                "link" -> {
                    WebViewActivity.openActivity(mContext, bannerDto.title, bannerDto.link, -1)
                }
                "product" -> {
                    GoodsDetailsActivity.openActivity(mContext, bannerDto.link.toInt())
                }
                "category" -> {
                    CommodityClassificationActivity.openActivity(
                        mContext,
                        CommodityClassificationActivity.FROM_GOODS_CENTER
                    )
                }
                "live" -> {
                }
            }
        }
    }

    private fun showEmptyView() {
        var size = 0
        when (tl_title.currentTab) {
            0 -> {
                size = goodAdpter.mData.size
                listView.apply {
                    layoutManager = GridLayoutManager(mContext, 2)
                    adapter = goodAdpter
                }
            }
            1 -> {
                size = liveAdpter.mData.size
                listView.apply {
                    layoutManager = LinearLayoutManager(mContext)
                    adapter = liveAdpter
                }
            }
            2 -> {
                size = groupAdpter.mData.size
                listView.apply {
                    layoutManager = LinearLayoutManager(mContext)
                    adapter = groupAdpter
                }
            }
            3 -> {
                size = biddingAdpter.mData.size
                listView.apply {
                    layoutManager = LinearLayoutManager(mContext)
                    adapter = biddingAdpter
                }
            }
        }
        val lp = status_view.layoutParams as ViewGroup.MarginLayoutParams
        when (size) {
            0 -> {
                lp.height = DensityUtil.dip2px(415f)
                status_view.showEmpty()
            }
            else -> {
                lp.height = ViewGroup.MarginLayoutParams.WRAP_CONTENT
                status_view.showContent()
            }
        }
        status_view.layoutParams = lp
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                areaDialog = null
                                mBinding.tvLoaction.text = this[0].name
                                regionId = this[0].id
                                lazyLoadData()
                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        my_banner.startAutoPlay()
    }

    override fun onPause() {
        super.onPause()
        my_banner.stopAutoPlay()
    }

    private fun initBanner() {
        my_banner.loadImage { _, model, view, _ ->
            setNomalImageUrl(
                view as ImageView,
                (model as BannerDto.SlideListBean).image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
    }
}